<?php

namespace App\Models;

use Validator;


class Admin extends BaseModel
{
    protected $table = "admin";

    public $timestamps = false;


    /* 用户模型自动验证 */
    protected $rules = [
        /* 验证用户名 */
        'username' => 'required|unique:admin|between:1,30',
        /* 验证密码 */
        'password' => 'required|between:6,30',
        'repassword' => 'required|between:6,30|same:password',
        'nickname' => 'unique:admin|between:1,30',
    ];

    protected $message = [
        /* 用户名验证信息 */
        'username.required' => '用户名必填',
        'username.unique' => '用户名被占用',
        'username.between' => '用户名长度不合法必须1-30位字符',
        /* 密码验证信息 */
        'password.required' => '密码必填',
        'password.between' => '密码长度不合法必须6-30位字符',
        'repassword.required' => '确认密码必填',
        'repassword.between' => '确认密码长度不合法必须6-30位字符',
        'repassword.same' => '两次密码不一致',
        /* 昵称验证信息 */
        'nickname.unique' => '昵称被占用',
        'nickname.between' => '昵称长度不合法必须1-30位字符',
    ];

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 添加管理员
     * @param  string $username 用户名
     * @param  string $password 用户密码
     * @return integer          注册成功-用户信息，注册失败-错误编号
     */
    public function add()
    {
        $data['username'] = trim(request('username'));
        $data['password'] = trim(request('password'));
        $data['repassword'] = trim(request('repassword'));
        $data['nickname'] = trim(request('nickname')) ? trim(request('nickname')) : $data['username'];
        $validator = $this->_validate($data);
        //验证失败
        if (!$validator) {
            return false;
        }
        unset($data['repassword']);
        $data['password'] = md5($data['password']);
        $data['reg_time'] = time();
        $data['reg_ip'] = request()->ip();
        $data['update_time'] = time();
        $data['reg_time'] = time();
        $data['status'] = 1;
        $res = $this->_add($data);
        if (!$res) {
            $this->error = '添加管理员失败！';
            return false;
        }
        return '添加管理员成功！'; //0-未知错误，大于0-注册成功
    }

    /**
     * 用户登录认证
     */
    public function login()
    {
        $username = request('username');
        $password = request('password');
        $where['username'] = $username;
        /* 获取用户数据 */
        $admin = $this->_getOne($where);
        if (!$admin || $admin['status'] != 1) {
            $this->error = '用户不存在或已被禁用！'; //应用级别禁用
            return false;
        }
        /* 验证用户密码 */
        if (md5($password) !== $admin['password']) {
            $this->error = '账号或密码错误';
            return false;
        }
        $this->updateLogin($admin); //更新用户登录信息
        $menu = new Menu();
        addSession('menus', $menu->getMenus());
        //记录行为
        $actionLog = new ActionLog();
        $actionLog->action_log('admin_login', 'admin', $admin['id'], $admin['id']);
        return true;
    }

    /**
     * 获取用户信息
     * @param  string $id 用户ID或用户名
     * @param  boolean $is_username 是否使用用户名查询
     * @return array                用户信息
     */
    public function info($id, $is_username = false)
    {
        $where = [];
        if ($is_username) { //通过用户名获取
            $where['username'] = $id;
        } else {
            $where['id'] = $id;
        }

        $admin = $this->_getOne($where, 'id,username,nickname,status');
        if (is_array($admin) && $admin['status'] == 1) {
            return [$admin['id'], $admin['username'], $admin['nickname']];
        } else {
            return -1; //用户不存在或被禁用
        }
    }

    /**
     * 检测用户信息
     * @param  string $field 用户名
     * @param  integer $type 用户名类型 1-用户名，2-用户邮箱，3-用户电话
     * @return integer         错误编号
     */
    public function checkField($field, $type = 1)
    {
        $data = [];
        switch ($type) {
            case 1:
                $data['username'] = $field;
                break;
            case 2:
                $data['email'] = $field;
                break;
            case 3:
                $data['mobile'] = $field;
                break;
            default:
                return 0; //参数错误
        }
        $validator = $this->_validate($data);
        //验证失败
        if (!$validator) {
            //返回所有错误信息
            return false;
        }
        return true;
    }

    /**
     * 更新用户登录信息
     * @param  integer $uid 用户ID
     */
    protected function updateLogin($admin)
    {
        /* 更新登录信息 */
        $data = [
            'last_login_time' => time(),
            'last_login_ip' => request()->ip()
        ];
        $this->_inc(['id' => $admin['id']], 'login', 1, $data);

        /* 记录登录SESSION和COOKIES */
        $auth = [
            'id' => $admin['id'],
            'username' => $admin['username'],
            'nickname' => $admin['nickname'],
            'last_login_time' => $admin['last_login_time'],
        ];
        session(['admin' => $auth]);
        session(['admin_sign' => data_auth_sign($auth)]);
    }

    /**
     * 更新用户信息
     * @param int $uid 用户id
     * @param string $password 密码，用来验证
     * @param array $data 修改的字段数组
     * @return true 修改成功，false 修改失败
     */
    public function updateUserFields($id, $password, $data)
    {
        if (empty($id) || empty($password) || empty($data)) {
            $this->error = '参数错误！';
            return false;
        }
        //更新前检查用户密码
        if (!$this->verifyUser($id, $password)) {
            $this->error = '验证出错：密码不正确！';
            return false;
        }
        $validator = $this->_validate($data);
        //验证失败
        if (!$validator) {
            return false;
        }
        //更新用户信息
        return $this->_update(['id' => $id], $data);
    }

    /**
     * 验证用户密码
     * @param int $uid 用户id
     * @param string $password_in 密码
     * @return true 验证成功，false 验证失败
     */
    public function verifyUser($id, $password_in)
    {
        $password = $this->_getOne(['id' => $id], 'password');
        if (md5($password_in) === $password) {
            return true;
        }
        return false;
    }

    public function getAdminList()
    {
        $nickname = request('nickname');
        $where['status'] = ['>=', 0];
        if (is_numeric($nickname)) {
            $where['id'] = $nickname;
        } else {
            $where['nickname'] = ['like', '%' . $nickname . '%'];
        }
        $rows = $this->_getPageList($where);
        $rows['data'] = int_to_string($rows['data']);
        return $rows;
    }

    public function editNickname()
    {
        //获取参数
        $nickname = trim(request('nickname'));
        $password = trim(request('password'));
        if (!$nickname) {
            $this->error = '请输入昵称';
            return false;
        }
        if (!$password) {
            $this->error = '请输入密码';
            return false;
        }
        $id = session('admin.id');
        //密码验证
        $where['id'] = $id;
        $result = $this->_getOne($where, 'password');
        if ($result['password'] !== md5($password)) {
            $this->error = '密码不正确';
            return false;
        }
        $where['id'] = ['<>', $id];
        $where['nickname'] = $nickname;
        $res = $this->_getOne($where);
        if ($res) {
            $this->error = '该昵称已存在';
            return false;
        }
        $res = $this->_save(['id' => $id, 'nickname' => $nickname]);
        if ($res) {
            $user = session('admin');
            $user['nickname'] = $nickname;
            addSession('admin', $user);
            addSession('admin_sign', data_auth_sign($user));
            return '修改昵称成功！';
        } else {
            $this->error = '修改昵称失败!';
            return false;
        }
    }

    public function editPassword()
    {
        $oldPassword = trim(request('old'));
        $newPassword = trim(request('password'));
        $repassword = trim(request('repassword'));

        if (!$oldPassword) {
            $this->error = '请输入原密码';
            return false;
        }
        if (!$newPassword) {
            $this->error = '请输入新密码';
            return false;
        }
        if (!$repassword) {
            $this->error = '请输入确认密码';
            return false;
        }
        if ($newPassword !== $repassword) {
            $this->error = '您输入的新密码与确认密码不一致';
            return false;
        }
        $where['id'] = session('admin.id');
        $data['password'] = md5($newPassword);
        $res = $this->_getOne($where);
        if ($res['password'] !== md5($oldPassword)) {
            $this->error = '原密码错误';
            return false;
        }
        if ($oldPassword == $newPassword) {
            $this->error = '新密码不能与原密码一样';
            return false;
        }
        $res = $this->_update($where, $data);
        if (!$res) {
            $this->error = '修改密码失败';
            return false;
        }
        return '修改密码成功!';
    }
}